# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from django.template import RequestContext
from django.db import transaction
from market.authentification import authentificatePlayer, authentificateUser
from market.models import UserProfile
from market.models import BetRoom, Strategy, AssetPercentageInStrategy, Fund, LastVisitedContract
from market.models import Asset, Player
from market.strategyAndFundHelper import getFundMtM, getPortfolioMtM

from market.stupidUserException import StupidUserException
from market.exceptionHandler import handleRequestPlayerPOSTWithExceptionWhenNotSuspended
from market.exceptionHandler import handleRequestBetroomAdminPOSTWithException

from datetime import datetime, date, time
import os, os.path
from market.baseCreator import constructRoomFromFiles
from market.baseSaver import saveRoomToFiles               
                

################################################################################################################
# gets the betroom from the user, the last visited betroom and if none, it check if theres is not just one betoom to admin for this user
# and returns it in case 
def getBetroomFromUser(request, betroom_list, alternative_response_list):
        
        if not( authentificateUser( request, alternative_response_list ) ):
                return False

		#get the last visted betroom
        up = request.user.get_profile()
			
        try:
                betroom = BetRoom.objects.get( name = up.nameOfTheLastVistedBetRoom )
        except Exception:
                alternative_response_list.append( HttpResponseRedirect("/betrooms/") )
                return False

        if not( betroom.personInCharge == request.user ):
                alternative_response_list.append( HttpResponseRedirect("/betrooms/") )
                return False

        betroom_list.append( betroom )
        return True


################################################################################################################
# betrooms for admin
def admin2Home(request):
        
        # authentification
        betroom_list = [] #the betroom to administrate
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( getBetroomFromUser(request, betroom_list, alternative_response_list) ):
                return alternative_response_list[0]

        # if the betroom is being launched, redirect until is launched
        if betroom_list[0].status < 1 :
                return HttpResponseRedirect("/createBetroom/step2/")
        
	return render_to_response( 'admin2/admin2Home.html',
                {'userName':request.user.username,'betroom':betroom_list[0]},
                context_instance=RequestContext(request) )
                
                
################################################################################################################
# web page to dump/create the data base from files
def saveAndCreateAdmin(request):
        
        # authentification
        betroom_list = [] #the betroom to administrate
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( getBetroomFromUser(request, betroom_list, alternative_response_list) ):
                return alternative_response_list[0]

        # if the betroom is being launched, redirect until is launched
        if betroom_list[0].status < 1 :
                return HttpResponseRedirect("/createBetroom/step2/")

	return render_to_response('admin2/admin2SaveAndCreate.html',
                {'userName':request.user.username,'betroom':betroom_list[0]},
                context_instance=RequestContext(request) )                


################################################################################################################
# web page for paying the divindend and suppress the assets
def deleteAssetAdmin(request):
        
        # authentification
        betroom_list = [] #the betroom to administrate
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( getBetroomFromUser(request, betroom_list, alternative_response_list) ):
                return alternative_response_list[0]

        # if the betroom is being launched, redirect until is launched
        if betroom_list[0].status < 1 :
                return HttpResponseRedirect("/createBetroom/step2/")

	return render_to_response('admin2/admin2DeleteAsset.html',
                {'userName':request.user.username,'betroom':betroom_list[0]},
                context_instance=RequestContext(request) )


################################################################################################################
# web page to add a player with market strategy
def addPlayerAdmin(request):
        
        # authentification
        betroom_list = [] #the betroom to administrate
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( getBetroomFromUser(request, betroom_list, alternative_response_list) ):
                return alternative_response_list[0]

        # if the betroom is being launched, redirect until is launched
        if betroom_list[0].status < 1 :
                return HttpResponseRedirect("/createBetroom/step2/")

	return render_to_response('admin2/admin2AddPlayer.html',
                {'userName':request.user.username,'betroom':betroom_list[0]},
                context_instance=RequestContext(request) )

################################################################################################################
# web page to settle one contract
def settleContractView(request):
        
        # authentification
        betroom_list = [] #the betroom to administrate
        alternative_response_list = [] #the answer to return if the player could not be authentificated with a dummy initialisation
        if not( getBetroomFromUser(request, betroom_list, alternative_response_list) ):
                return alternative_response_list[0]

        # if the betroom is being launched, redirect until is launched
        if betroom_list[0].status < 1 :
                return HttpResponseRedirect("/createBetroom/step2/")
        # in the by contract room, the admin is also a player...
        player = Player.objects.get( userBeingThisPlayer = request.user, mainStrategy__betroom = betroom_list[0] )
        contractList = LastVisitedContract.objects.filter( player = player )
        hasUnsettledContract = False
        if len( contractList ) == 1:
                if contractList[0].contract.expiry < datetime.now():
                        contractList[0].settlementSatus = -1
                        contractList[0].save()
                if contractList[0].contract.settlementStatus == -1:
                        hasUnsettledContract = True
                        dictio = {'userName':request.user.username,'betroom':betroom_list[0], 'contract':contractList[0].contract }
        if not( hasUnsettledContract ):
                dictio = {'userName':request.user.username,'betroom':betroom_list[0], 'contractFixed':'' }

	return render_to_response('admin2/settleContract.html',dictio , context_instance=RequestContext(request) )





                

